package com.tyut.pojo;


import com.tyut.utils.ThreadLocalUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Map;

//统一响应结果
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Result<T> {
    private Integer code;//业务状态码  0-成功  1-失败
    private String msg;//提示信息
    private T data;//响应数据
    private String role;

    //快速返回操作成功响应结果(带响应数据)

    public Result(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }


    public static <E> Result<E> success(E data,String role) {
        return new Result<>(0,"登录成功",data,role);
    }

    public static <E> Result<E> success(E data) {
        Map<String,Object> map = ThreadLocalUtil.get();
        if(map == null){
            return new Result<>(0,"操作成功",data);
        }
        String role = (String) map.get("userRole");
        return new Result<>(0, "操作成功", data,role);
    }

    //快速返回操作成功响应结果
    public static Result success() {
        Map<String,Object> map = ThreadLocalUtil.get();
        if(map == null){
            return new Result<>(0,"操作成功",null);
        }
        String role = (String) map.get("userRole");
        return new Result(0, "操作成功", null,role);
    }

    public static Result error(String message) {
        Map<String,Object> map = ThreadLocalUtil.get();
        if(map == null){
            return new Result(1, message, null);
        }
        String role = null;
        try {
            role = (String) map.get("userRole");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new Result(1, message, null,role);
    }
}
